package com.frxuexi.sign

import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.SignBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.sign.databinding.ActivitySignAddBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask


@Route(path = "/sign/SignAddActivity")
@AndroidEntryPoint
class SignAddActivity : BaseActivity<ActivitySignAddBinding, SignIntent, SignViewModel>() {
    var mLocationClient:LocationClient?=null
    var myLocationListener:MyLocationListener?=null
    override val binding: ActivitySignAddBinding by lazy {
        ActivitySignAddBinding.inflate(
            layoutInflater
        )
    }
    override val vm: SignViewModel by viewModels<SignViewModel>()

    var timer: Timer? = null
    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*>->{
                        ToastUtils.showLong("打卡成功")
                    }
                    else->{}
                }
            }

        }
    }

    override fun initView() {


        lifecycleScope.launch(Dispatchers.IO) {
            timer = Timer()
            timer!!.schedule(timerTask {
                lifecycleScope.launch (Dispatchers.Main){
                    binding.signTime.setText(vm.getTime(System.currentTimeMillis()))
                }
            }, 0, 1000)
        }
        val currentTime= System.currentTimeMillis()
        val week = TimeUtils.getChineseWeek(currentTime).replace("周", "星期")
        binding.signDate.setText("${vm.getData(currentTime)} ${week}")

        getLoc()

        //morning,2025-07-01
        val sign = SPUtils.getInstance().getString("sign", "")
        if(sign.isNotEmpty()){
            val split = sign.split(",")
            //获取今天日期
            val today = vm.getData(System.currentTimeMillis())
            //如果和今天日期一样，说明今天打过卡
            if(split[1]==today){
                //已经打了下班卡
                if(split[0]!="morning"){
                    binding.btnSign.isEnabled=false
                }else{//打了上班卡
                    binding.signTvdaka.setText("下午打卡")
                    binding.signTvtime.setText("14:00-18:00")
                }
            }
        }

        binding.btnSign.setOnClickListener {
            val dataTime = vm.getDataTime(System.currentTimeMillis())
            var morning=""
            var after=""
            var status="正常"
            //打上班卡
            if(binding.signTvdaka.text.toString()=="上午打卡"){
                SPUtils.getInstance().put("sign","morning,${dataTime.split(" ")[0]}")
                binding.signTvdaka.setText("下午打卡")
                binding.signTvtime.setText("14:00-18:00")
                morning=dataTime
                if(dataTime.split(" ")[1]>"09:00:00"){
                    status="迟到"
                }
            }else{//打下班卡
                SPUtils.getInstance().put("sign","after,${dataTime.split(" ")[0]}")
                binding.btnSign.isEnabled=false
                after=dataTime
                if(dataTime.split(" ")[1]<"18:00:00"){
                    status="早退"
                }
            }
            val item = SignBeanItem(
                after,
                SPUtils.getInstance().getString("lat"),
                null,
                "天津市",
                morning,
                status,
                SPUtils.getInstance().getInt(Const.UID)
            )
            vm.sendIntent(SignIntent.sign(item))

        }
    }

    private fun getLoc() {
        try {
            LocationClient.setAgreePrivacy(true)

            //定位初始化
            mLocationClient = LocationClient(this)

//通过LocationClientOption设置LocationClient相关参数

//通过LocationClientOption设置LocationClient相关参数
            val option = LocationClientOption()
            option.isOpenGps = true // 打开gps

            option.setCoorType("bd09ll") // 设置坐标类型

            option.setScanSpan(1000)

//设置locationClientOption

//设置locationClientOption
            mLocationClient!!.locOption = option

//注册LocationListener监听器

//注册LocationListener监听器
            myLocationListener = MyLocationListener()
            mLocationClient!!.registerLocationListener(myLocationListener)
//开启地图定位图层
//开启地图定位图层
            mLocationClient!!.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            val latitude = location.latitude //获取纬度信息
            val longitude = location.longitude //获取经度信息
            val radius = location.radius //获取定位精度，默认值为0.0f
            val coorType = location.coorType
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            val errorCode = location.locType
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            SPUtils.getInstance().put("lat","${latitude},${longitude}")
            Log.i("===","${latitude},${longitude}")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
        mLocationClient?.unRegisterLocationListener(myLocationListener)
        myLocationListener=null
        mLocationClient?.stop();
        mLocationClient=null
//        mBaiduMap.setMyLocationEnabled(false);
//        mMapView.onDestroy();
//        mMapView = null;
    }
}


